import Vue, { getCurrentInstance, Ref, ref, unRef } from "vue";
import { Loading } from 'element-ui';
import { ElLoadingComponent } from "element-ui/types/loading";

export const useCurrentInstance = (): [Vue, Function]=> {
  const { proxy: currentCtx } = getCurrentInstance() || {};

  const setData = (key: string, value: any) => {
    currentCtx && (currentCtx.$data[key] = value);
  };

  return [
    currentCtx as unknown as Vue,
    setData
  ];
};

export const useState = <T> (params: T): [Ref<T>, (data: T)=> void] => {
  const state = ref(params) as Ref<T>;
  const setState = (data: T) => {
    state.value = data;
  };

  return [state, setState];
};


export const useRouter = ()=> {
  const [ctx] = useCurrentInstance();
  const query = ctx && ctx?.$route.query;
  const params = ctx && ctx?.$route.params;
  const router =  ctx && ctx.$router;
  const route =  ctx && ctx.$route;
  return {
    router,
    route,
    query,
    params
  };
};

export const useServiceLoading = ()=> {
  const loadingInstanceRef: Ref<ElLoadingComponent | null>= ref(null);

  const showServiceLoading = () => {
    loadingInstanceRef.value = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
  };


  const hideServiceLoading = ()=> {
    loadingInstanceRef.value?.close();
  };

  return {
    loadingInstanceRef,
    showServiceLoading,
    hideServiceLoading
  };
};
